from fastapi import APIRouter, HTTPException, Depends, Query
from typing import List
from api.models.schemas import (
    FrameworkInfo, 
    FrameworkWorkHoursResponse, 
    ApiResponse,
    WorkLogDetail
)
from database import get_query_helper, WorkHoursQueryHelper
from utils.logger import get_logger

# 获取日志记录器
logger = get_logger(__name__)

router = APIRouter()


def get_query_helper_dependency() -> WorkHoursQueryHelper:
    """获取查询辅助器的依赖注入"""
    return get_query_helper()


@router.get("/frameworks", response_model=ApiResponse, summary="获取所有部门信息")
async def get_all_frameworks(
    query_helper: WorkHoursQueryHelper = Depends(get_query_helper_dependency)
):
    """
    获取所有部门信息
    
    返回系统中所有部门的基本信息
    """
    try:
        logger.info("🏢 获取所有部门信息")
        
        frameworks_data = query_helper.get_all_frameworks()
        
        # 转换为响应模型
        frameworks_list = []
        for framework in frameworks_data:
            frameworks_list.append(FrameworkInfo(**framework))
        
        logger.info(f"✅ 获取部门信息成功: {len(frameworks_list)} 个部门")
        
        return ApiResponse(
            code=200,
            message="获取部门信息成功",
            data=frameworks_list
        )
        
    except Exception as e:
        logger.error(f"❌ 获取部门信息失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取部门信息失败: {str(e)}")


@router.get("/frameworks/{framework_name}/worklogs", response_model=ApiResponse, summary="按部门查询工时")
async def get_framework_worklogs(
    framework_name: str,
    start_date: str = Query(..., description="开始日期 (YYYY-MM-DD)"),
    end_date: str = Query(..., description="结束日期 (YYYY-MM-DD)"),
    query_helper: WorkHoursQueryHelper = Depends(get_query_helper_dependency)
):
    """
    按部门查询工时
    
    根据部门名称和时间范围查询工时记录
    """
    try:
        logger.info(f"🏢 查询部门工时: {framework_name}, {start_date} - {end_date}")
        
        # 获取部门工时记录
        work_logs = query_helper.get_framework_worklogs(framework_name, start_date, end_date)
        
        # 计算统计数据
        total_hours = sum(log.get('WorkHour', 0) for log in work_logs)
        
        # 统计人员数量
        people_set = set()
        for log in work_logs:
            people_set.add(log.get('PeopleName'))
        total_people = len(people_set)
        
        # 转换为响应模型
        work_log_details = []
        for log in work_logs:
            work_log_details.append(WorkLogDetail(**log))
        
        response_data = FrameworkWorkHoursResponse(
            framework_name=framework_name,
            total_hours=total_hours,
            total_people=total_people,
            work_logs=work_log_details
        )
        
        logger.info(f"✅ 部门工时查询完成: {len(work_logs)} 条记录, {total_hours:.1f} 小时, {total_people} 人")
        
        return ApiResponse(
            code=200,
            message="查询成功",
            data=response_data.dict()
        )
        
    except Exception as e:
        logger.error(f"❌ 部门工时查询失败: {e}")
        raise HTTPException(status_code=500, detail=f"查询失败: {str(e)}")


@router.get("/frameworks/{framework_name}/summary", response_model=ApiResponse, summary="部门工时总结")
async def get_framework_summary(
    framework_name: str,
    start_date: str = Query(..., description="开始日期 (YYYY-MM-DD)"),
    end_date: str = Query(..., description="结束日期 (YYYY-MM-DD)"),
    query_helper: WorkHoursQueryHelper = Depends(get_query_helper_dependency)
):
    """
    部门工时总结
    
    获取指定部门在指定时间范围内的工时统计总结
    """
    try:
        logger.info(f"📊 生成部门工时总结: {framework_name}, {start_date} - {end_date}")
        
        # 获取部门工时记录
        work_logs = query_helper.get_framework_worklogs(framework_name, start_date, end_date)
        
        # 生成统计信息
        summary = generate_framework_summary(framework_name, work_logs, start_date, end_date)
        
        logger.info(f"✅ 部门工时总结生成完成: {framework_name}")
        
        return ApiResponse(
            code=200,
            message="总结生成成功",
            data={
                "framework_name": framework_name,
                "start_date": start_date,
                "end_date": end_date,
                "summary": summary
            }
        )
        
    except Exception as e:
        logger.error(f"❌ 部门工时总结生成失败: {e}")
        raise HTTPException(status_code=500, detail=f"总结生成失败: {str(e)}")


def generate_framework_summary(framework_name: str, work_logs: List, start_date: str, end_date: str) -> str:
    """生成部门工时总结"""
    
    total_hours = sum(log.get('WorkHour', 0) for log in work_logs)
    
    # 按员工统计
    people_stats = {}
    for log in work_logs:
        name = log.get('PeopleName', '未知')
        if name not in people_stats:
            people_stats[name] = {'hours': 0, 'logs': 0}
        people_stats[name]['hours'] += log.get('WorkHour', 0)
        people_stats[name]['logs'] += 1
    
    # 按项目统计
    project_stats = {}
    for log in work_logs:
        project_name = log.get('ProjectName', '未知项目')
        if project_name not in project_stats:
            project_stats[project_name] = {'hours': 0, 'logs': 0}
        project_stats[project_name]['hours'] += log.get('WorkHour', 0)
        project_stats[project_name]['logs'] += 1
    
    # 生成总结
    summary = f"## {framework_name} 部门工时统计总结\n\n"
    summary += f"**时间范围**: {start_date} 至 {end_date}\n\n"
    summary += f"**总体统计**:\n"
    summary += f"- 总工时: {total_hours:.1f} 小时\n"
    summary += f"- 总记录数: {len(work_logs)} 条\n"
    summary += f"- 涉及员工: {len(people_stats)} 人\n"
    summary += f"- 涉及项目: {len(project_stats)} 个\n"
    summary += f"- 人均工时: {total_hours / max(1, len(people_stats)):.1f} 小时\n\n"
    
    if people_stats:
        summary += "**员工工时分布**:\n"
        sorted_people = sorted(people_stats.items(), key=lambda x: x[1]['hours'], reverse=True)
        for name, stats in sorted_people:
            percentage = (stats['hours'] / total_hours * 100) if total_hours > 0 else 0
            summary += f"- {name}: {stats['hours']:.1f} 小时 ({percentage:.1f}%) - {stats['logs']} 条记录\n"
        summary += "\n"
    
    if project_stats:
        summary += "**项目工时分布**:\n"
        sorted_projects = sorted(project_stats.items(), key=lambda x: x[1]['hours'], reverse=True)
        for project, stats in sorted_projects:
            percentage = (stats['hours'] / total_hours * 100) if total_hours > 0 else 0
            summary += f"- {project}: {stats['hours']:.1f} 小时 ({percentage:.1f}%) - {stats['logs']} 条记录\n"
        summary += "\n"
    
    summary += "**备注**: 此总结由系统自动生成。"
    
    return summary 